<template>
  <div>
    <customDialog
      :title="`${title}轮播图`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="800"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-position="right"
          label-width="90px"
          class="form_box"
        >
          <el-row>
            <el-col :span="18">
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入名称"
                  maxlength="15"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="标题" prop="title">
                <el-input
                  v-model="formData.title"
                  placeholder="请输入标题"
                  clearable
                  maxlength="10"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="跳转链接" prop="link" class="link">
                <el-tooltip
                  placement="top"
                  effect="dark"
                  content="播放页跳转链接示例：/pages/hot/play?id=剧目ID(必填)&episode=集数(必填)"
                >
                  <el-icon
                    class="tooltip_color"
                    style="
                      margin: 0 10px 0 -10px;
                      font-size: 18px;
                      cursor: pointer;
                    "
                  >
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                <el-input
                  v-model="formData.link"
                  placeholder="请输入跳转链接"
                  clearable
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="轮播图片" prop="path" class="path">
                <div v-if="formData.path" class="img_box">
                  <el-image
                    style="height: 100px; border-radius: 4px"
                    :src="`https://theater-static-1320245876.cos.ap-guangzhou.myqcloud.com/${formData?.path}?${randN}`"
                    :zoom-rate="1.2"
                    :preview-src-list="[
                      `https://theater-static-1320245876.cos.ap-guangzhou.myqcloud.com/${formData?.path}?${randN}`,
                    ]"
                    :initial-index="1"
                    fit="contain"
                  />
                  <el-icon @click="deleteImg" class="delete_icon">
                    <CircleClose />
                  </el-icon>
                </div>
                <uploadFile v-else @updateFileList="seccessFile" />
                <p style="font-size: 12px">
                  温馨提示：为了小程序美观，轮播图支持jpeg/jpg/png格式，设计尺寸推荐750*350，文件大小
                  2Mb 以内
                </p>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row />
          <el-row>
            <el-col :span="18">
              <el-form-item label="描述" prop="description">
                <el-input
                  v-model="formData.description"
                  placeholder="请输入描述"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  clearable
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="是否启用" prop="enabled">
                <el-switch
                  style="

--el-switch-on-color: #13ce66"
                  v-model="formData.enabled"
                  inline-prompt
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import { ref, reactive, toRefs, computed } from "vue";
import { ElMessage } from "element-plus";
import { CircleClose, QuestionFilled } from "@element-plus/icons-vue";
import customDialog from "@/components/CustomDialog/index.vue";
import uploadFile from "@/components/UploadFile/index.vue";
import { addBanner, updateBanner } from "@/api/operateCenter/banner/index";
import type { FormInstance } from "element-plus";
import { cloneDeep, debounce } from "lodash-es";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = {
  id: undefined,
  name: "",
  title: "",
  description: "",
  link: "",
  path: "",
  enabled: true,
};
const formData = ref(Object.assign({}, form));
const title = ref<string>("");
const randN = Math.floor(Math.random() * 100000); // 生成随机数，保证每个图片不走浏览器缓存

const rules = reactive({
  name: [{ required: true, message: "请填写名称", trigger: "blur" }],
  title: [{ required: true, message: "请填写标题", trigger: "blur" }],
  // description: [{ required: true, message: "请填写描述信息", trigger: "blur" }],
  link: [{ required: true, message: "请填写跳转链接", trigger: "blur" }],
  path: [{ required: true, message: "请选择图片", trigger: "change" }],
});

// 文件上传成功
const seccessFile = (file: Array<any>) => {
  let fileData = file[0].raw;
  const formFile = new FormData();
  formFile.append("file", fileData);
  request
    .post(`/api/BannerImages/upload`, formFile)
    .then((res: Record<string, any>) => {
      formData.value.path = res.data;
    });
};

// 删除授权材料
const deleteImg = () => {
  formData.value.path = "";
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (title.value == "编辑") {
        URL = updateBanner;
      } else {
        URL = addBanner;
      }
      URL(formData.value).then(() => {
        ElMessage.success(`${title.value}成功`);
        dialogVisible.value = false;
        emit("success");
        closeDialog(ruleFormRef.value);
      });
    }
  });
}, 150);

// 父级电子显示dialog
const showDialog = async (val: any) => {
  console.log("显示弹窗----", val);
  dialogVisible.value = true;
  title.value = val ? "编辑" : "新增";
  if (val) {
    formData.value = cloneDeep(val);
  }
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;

  .link {
    margin-left: -18px;

    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }

    :deep(.el-form-item__content > .el-form-item__error) {
      left: 18px;
    }
  }

  .path {
    :deep(.el-form-item__content) {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  .img_box {
    position: relative;
    display: flex;
    align-items: center;
    // height: 120px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;

    .delete_icon {
      position: absolute;
      top: 3px;
      right: 0;
      color: #666;
      cursor: pointer;
    }
  }
}
</style>
